#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015-2020 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

from collections import OrderedDict
from backtrader.utils.datehelper import *
from backtrader.utils.py3 import range
from backtrader import Analyzer

"""
分阶段统计收益
"""


class RangeReturn(Analyzer):
    '''
    This analyzer calculates the AnnualReturns by looking at the beginning
    and end of the year

    Params:

      - (None)

    Member Attributes:

      - ``rets``: list of calculated annual returns

      - ``ret``: dictionary (key: year) of annual returns

    **get_analysis**:

      - Returns a dictionary of annual returns (key: year)
    '''

    def cal_range_ret(self, data, filter_dt):
        start_value = float('NaN')
        for i in range(len(self.data) - 1, -1, -1):
            dt = self.data.datetime.date(-i)
            if dt < filter_dt:
                continue
            else:
                start_value = self.strategy.stats.broker.value[-i]
                break
        return self.strategy.broker.get_value() / start_value - 1

    def stop(self):
        self.ret = OrderedDict()
        end_time = self.data.datetime.date(0)

        for m in ["1month", "3month", "6month", "ytd"]:
            month_date, _month_key = recent_date(end_time, m)
            self.ret[_month_key] = self.cal_range_ret(self.data, month_date)

    def get_analysis(self):
        return self.ret
